/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.grammar.util;

import org.proteusframework.platformservice.grammar.expression.*;
import org.proteusframework.platformservice.grammar.expression.StringValue;
import org.proteusframework.platformservice.grammar.expression.operators.arithmetic.*;
import org.proteusframework.platformservice.grammar.expression.operators.conditional.AndExpression;
import org.proteusframework.platformservice.grammar.expression.operators.conditional.OrExpression;
import org.proteusframework.platformservice.grammar.expression.operators.relational.*;
import org.proteusframework.platformservice.grammar.schema.Column;

import java.util.Iterator;

/**
 * Serialize an {@link org.proteusframework.platformservice.grammar.expression.IExpression} as a String.
 */
public class ExpressionSerializer implements IExpressionVisitor, IItemsListVisitor
{

    protected StringBuffer buffer;
    protected boolean useBracketsInExprList = true;
    protected IExpressionVisitor expressionVisitor;

    public ExpressionSerializer()
    {
    }

    /**
     * @param expressionVisitor a ExpressionVisitor to serialize an Expression.
     * @param buffer            String representation of the expression
     */
    public ExpressionSerializer(IExpressionVisitor expressionVisitor, StringBuffer buffer)
    {
        this.expressionVisitor = expressionVisitor;
        this.buffer = buffer;
    }

    public StringBuffer getBuffer()
    {
        return buffer;
    }

    public void setBuffer(StringBuffer buffer)
    {
        this.buffer = buffer;
    }

    public void visit(Addition addition)
    {
        visitBinaryExpression(addition, " + ");
    }

    public void visit(AndExpression andExpression)
    {
        visitBinaryExpression(andExpression, " AND ");
    }

    public void visit(Between between)
    {
        between.getLeftExpression().accept(this);
        if (between.isNot())
            buffer.append(" NOT");

        buffer.append(" BETWEEN ");
        between.getBetweenExpressionStart().accept(this);
        buffer.append(" AND ");
        between.getBetweenExpressionEnd().accept(this);

    }

    public void visit(Division division)
    {
        visitBinaryExpression(division, " / ");

    }

    public void visit(DoubleValue doubleValue)
    {
        buffer.append(doubleValue.getValue());

    }

    public void visit(EqualsTo equalsTo)
    {
        visitBinaryExpression(equalsTo, " = ");
    }

    public void visit(GreaterThan greaterThan)
    {
        visitBinaryExpression(greaterThan, " > ");
    }

    public void visit(GreaterThanEquals greaterThanEquals)
    {
        visitBinaryExpression(greaterThanEquals, " >= ");

    }

    public void visit(InExpression inExpression)
    {

        inExpression.getLeftExpression().accept(this);
        if (inExpression.isNot())
            buffer.append(" NOT");
        buffer.append(" IN ");

        inExpression.getItemsList().accept(this);
    }

    public void visit(InverseExpression inverseExpression)
    {
        buffer.append("-");
        inverseExpression.getExpression().accept(this);
    }

    public void visit(IsNullExpression isNullExpression)
    {
        isNullExpression.getLeftExpression().accept(this);
        if (isNullExpression.isNot())
        {
            buffer.append(" IS NOT NULL");
        } else
        {
            buffer.append(" IS NULL");
        }
    }

    public void visit(JdbcParameter jdbcParameter)
    {
        buffer.append("?");

    }

    public void visit(LikeExpression likeExpression)
    {
        visitBinaryExpression(likeExpression, " LIKE ");

    }

    public void visit(ExistsExpression existsExpression)
    {
        if (existsExpression.isNot())
        {
            buffer.append(" NOT EXISTS ");
        } else
        {
            buffer.append(" EXISTS ");
        }
        existsExpression.getRightExpression().accept(this);
    }

    public void visit(LongValue longValue)
    {
        buffer.append(longValue.getStringValue());

    }

    public void visit(MinorThan minorThan)
    {
        visitBinaryExpression(minorThan, " < ");

    }

    public void visit(MinorThanEquals minorThanEquals)
    {
        visitBinaryExpression(minorThanEquals, " <= ");

    }

    public void visit(Multiplication multiplication)
    {
        visitBinaryExpression(multiplication, " * ");

    }

    public void visit(NotEqualsTo notEqualsTo)
    {
        visitBinaryExpression(notEqualsTo, " <> ");

    }

    public void visit(NullValue nullValue)
    {
        buffer.append("NULL");

    }

    public void visit(OrExpression orExpression)
    {
        visitBinaryExpression(orExpression, " OR ");

    }

    public void visit(Parenthesis parenthesis)
    {
        if (parenthesis.isNot())
            buffer.append(" NOT ");

        buffer.append("(");
        parenthesis.getExpression().accept(this);
        buffer.append(")");

    }

    public void visit(StringValue stringValue)
    {
        buffer.append("'" + stringValue.getValue() + "'");

    }

    public void visit(Subtraction subtraction)
    {
        visitBinaryExpression(subtraction, "-");

    }

    private void visitBinaryExpression(BinaryExpression binaryExpression, String operator)
    {
        if (binaryExpression.isNot())
            buffer.append(" NOT ");
        binaryExpression.getLeftExpression().accept(this);
        buffer.append(operator);
        binaryExpression.getRightExpression().accept(this);

    }

    public void visit(Column tableColumn)
    {
        buffer.append(tableColumn.getColumnName());
    }

    public void visit(ExpressionList expressionList)
    {
        if (useBracketsInExprList)
            buffer.append("(");
        for (Iterator iter = expressionList.getExpressions().iterator(); iter.hasNext(); )
        {
            IExpression expression = (IExpression) iter.next();
            expression.accept(this);
            if (iter.hasNext())
                buffer.append(", ");
        }
        if (useBracketsInExprList)
            buffer.append(")");
    }


    public void visit(DateValue dateValue)
    {
        buffer.append("{d '" + dateValue.getValue().toString() + "'}");
    }

    public void visit(TimestampValue timestampValue)
    {
        buffer.append("{ts '" + timestampValue.getValue().toString() + "'}");
    }

    public void visit(TimeValue timeValue)
    {
        buffer.append("{t '" + timeValue.getValue().toString() + "'}");
    }

    public void visit(Concat concat)
    {
        visitBinaryExpression(concat, " || ");
    }

    public void visit(BitwiseAnd bitwiseAnd)
    {
        visitBinaryExpression(bitwiseAnd, " & ");
    }

    public void visit(BitwiseOr bitwiseOr)
    {
        visitBinaryExpression(bitwiseOr, " | ");
    }

    public void visit(BitwiseXor bitwiseXor)
    {
        visitBinaryExpression(bitwiseXor, " ^ ");
    }

}